<template>
  <edit-dialog
    ref="dialog"
    class="ml-1"
    width="600px"
    custom-class="create-sdk-dialog"
    :loading="isLoading"
    :submit-loading="isLoading"
    v-bind="$attrs"
    @submit="handleSubmit"
    @opened="opened"
  >
    <template-form
      ref="form"
      v-loading="isLoading"
      label-width="130px"
      class="hm-form"
      :data="datas"
      :configs="createFields"
      :params="params"
    />
  </edit-dialog>
</template>

<script>
import { createSdkFields } from '../config'
import EditDataMixin from 'modules/mixins/edit-data'
import SectionLoadMixin from 'modules/mixins/section-loading'
import { getSdkActivityDetail } from 'dependencies/api/sdk-management'

export default {
  mixins: [EditDataMixin, SectionLoadMixin],
  props: {
    isEdit: Boolean,
    id: {
      type: [Number, String],
      default: 0
    }
  },
  data() {
    return {
      datas: {},
      editLoading: false
    }
  },
  computed: {
    createFields() {
      return createSdkFields.getFields({
        params: {
          ...this.datas
        },
        data: this.params
      })
    }
  },
  methods: {
    async handleSubmit(callback) {
      const params = await this.$refs.form.submit()
      params.targetApps && (params.targetApps = params.targetApps.split(','))
      this.isEdit && (params.id = this.id)
      try {
        this.loading()
        this.$emit('submit', {
          params,
          callback: success => {
            this.loaded()
            success && callback()
          }
        })
      } catch (error) {
        console.log(error)
        this.loaded()
      }
    },
    opened() {
      this.resetParams()
      // 详情数据
      !this.isEdit && this.$refs.form.resetParams()
      if (this.isEdit && this.id) {
        this.getDetail()
      }
    },
    async getDetail() {
      try {
        this.loading()
        const data = await getSdkActivityDetail({
          id: this.id
        })
        if (data.success) {
          this.datas = {
            ...data.data
          }
          this.params = { ...data.data, activityTime: [data.data.begDate, data.data.endDate] }
          if (Array.isArray(this.params.targetApps) && this.params.targetApps.length) {
            this.params.targetApps = this.params.targetApps.join(',')
          } else {
            this.params.targetApps = ''
          }
        }
      } catch (error) {
        console.error(error)
      } finally {
        this.loaded()
      }
    }
  }
}
</script>

<style lang="scss">
.sort-input__number .el-input--medium {
  width: 100%!important;
}
.hm-form .el-radio-group {
  line-height: unset;
}
.create-sdk-dialog {
 .el-dialog__body {
    max-height: 700px;
    overflow: auto;
  }
}
</style>
